<?php

namespace app\helper;

use app\enum\StatusCode;

class Result
{
    /** 数据格式
     * @param int $code
     * @param string $msg
     * @param mixed|null $data
     * @return array
     */
    public static function format(int $code, string $msg, mixed $data = null): array
    {
        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ];
    }

    /** json格式
     * @param int $code
     * @param string $msg
     * @param mixed|null $data
     * @return \support\Response|\think\response\Json
     */
    public static function json(int $code, string $msg, mixed $data = null): \support\Response|\think\response\Json
    {
        if (!$msg) {
            $msg = StatusCode::tryFrom($code)?->msg();
        }
        return json(self::format($code, $msg, $data));
    }

    /** 成功的json
     * @param string $msg
     * @param mixed|null $data
     * @param int $code
     * @return \support\Response|\think\response\Json
     */
    public static function success(string $msg = 'ok', mixed $data = null, int $code = StatusCode::SUCCESS->value): \support\Response|\think\response\Json
    {
        return self::json($code, $msg, $data);
    }

    /** 失败的json
     * @param string $msg
     * @param mixed|null $data
     * @param int $code
     * @return \support\Response|\think\response\Json
     */
    public static function fail(int $code = StatusCode::FAIL->value, string $msg = 'error', mixed $data = null): \support\Response|\think\response\Json
    {
        return self::json($code, $msg, $data);
    }


}
